<?php

/**
 * Subclass for performing query and update operations on the 'user_container' table.
 *
 * 
 *
 * @package lib.model
 */ 
class UserContainerPeer extends BaseUserContainerPeer
{
	static function isUserRegistered($container_userid,$container_os_id){
		$c = new Criteria();
		$c->add(ContainerPeer::OPENSOCIAL_NAME,$container_os_id);
		$c->add(UserContainerPeer::CONTAINER_USERID,$container_userid);
		$c->addJoin(UserContainerPeer::CONTAINER_ID,ContainerPeer::ID);
		return UserContainerPeer::doCount($c);
	} 	
	
	static public function createNewUserFromRequest($userid,sfWebRequest $request){
		try {
			$osUser = new OpenSocialContainerUser($userid);
			$os_container = ContainerPeer::getByOpenSocialName($osUser->getContainerId());
			//Okee, so far so good, nu gebruiker ophalen
			$c = new Criteria();
			$c->add(UserContainerPeer::CONTAINER_ID,$os_container->getId());
			$c->add(UserContainerPeer::CONTAINER_USERID, $osUser->getId());
			$c->addJoin(UserPeer::ID,UserContainerPeer::USER_ID);
			$existing = UserPeer::doSelectOne($c);
			if($existing){
				$e = new LypoUserException("Existing user found");
				$e->setUser($existing);
				throw $e;				
			}

			//Maak nieuwe LypoUser aan!
			$newuser = new User();
			$newuser->updateFromWebRequest($request);
			$newuser->save();
			
			//Okee ook alle antwoorden updaten/inserten (extracten uit lypo signature)
			StatementAnswerPeer::createUsersAnswersFromLypoSignature($newuser->getId(),$newuser->getLypoSignature());
			
			
			//Okee nu ook een UserContainer record maken!
			$user_container = new UserContainer();
			$user_container->setContainerUserid($osUser->getId());
			$user_container->setContainer($os_container);
			$user_container->setUserId($newuser->getId());
			$user_container->save();
			
			return $newuser;
			
		}catch(Exception $e){
			throw $e;
		}
	}	

	
	/* Merged $otheruser met deze user:
	*  - maakt nieuwe container_user entry aan.
	*  - oude data blijft in principe bewaard
	*  - wat doen we met oude data? 
	*/
	static public function mergeUsers(User $main_user, $userid_to_merge){
		try {
		$osUser = new OpenSocialContainerUser($userid_to_merge);
		$container = ContainerPeer::getByOpenSocialName($osUser->getContainerId());
		//Eventuele oude koppelingen van deze gebruiker van die container weghalen
		$c = new Criteria();
		$c->add(UserContainerPeer::CONTAINER_ID,$container->getId());
		$c->add(UserContainerPeer::CONTAINER_USERID,$osUser->getId());
		UserContainerPeer::doDelete($c);
		
		$merged = new UserContainer();
		$merged->setContainerId($container->getId());
		$merged->setContainerUserid($osUser->getId());
		$merged->setUserId($main_user->getId());
		$merged->save();
		} catch (sfException $e){
			throw $e;
		}
	}
	
}
